<?php
class CrudHandler {

	private $clazz;
	public $plural;
	public $single;
	
	public $data;
	
	public function CrudHandler($clazz, $data) {
		$this->clazz = $clazz;
		$this->single = strtolower($clazz);
		$this->plural = $this->single . 's';
		$this->data = $data;
		$this->setObjectAttributes();
	}
	
	public function indexAction($requestData) {
		$method = new ReflectionMethod($this->clazz, 'getAll');
		$this->data['objects'] = $method->invoke(null);
	}
	
	public function editAction($requestData) {
		if(@$requestData['arg0'] !== '') {
			$method = new ReflectionMethod($this->clazz, 'get');
			$this->data['object'] = $method->invoke(null, $requestData['arg0']);
		}else {
			$this->data['object'] = new $this->clazz(array());
		}
	}
	
	public function saveAction($requestData) {
		$requestData['id'] = $requestData[$this->single];
		$object = new $this->clazz($requestData);
		$validation = $object->validate();
		if(is_array($validation)) {
			$this->addValidationErrors($validation);
			$this->data['object'] = $object;
			BaseController::forward($this->plural, 'edit');
		}else {
			if($object->id == '') {
				$object->save();
				Adroit::$alerts->addAlert($this->clazz . ' has been saved', AdroitAlertHandler::$TYPE_SUCCESS);
			}else {
				$object->update();
				Adroit::$alerts->addAlert($this->clazz . ' has been updated', AdroitAlertHandler::$TYPE_SUCCESS);
			}
			BaseController::redirect('admin/' . $this->plural, 'edit/' . $object->id);
		}
	}
	
	public function deleteAction($requestData) {
		if($requestData[$this->single] != '') {
			$method = new ReflectionMethod($this->clazz, 'get');
			$method->invoke(null, $requestData[$this->single])->delete();
			Adroit::$alerts->addAlert($this->clazz . ' deleted', AdroitAlertHandler::$TYPE_SUCCESS);
		}
		BaseController::redirect('admin/' . $this->plural . '/');
	}
	
	private function setObjectAttributes() {
		$obj = new $this->clazz(array());
		foreach($obj AS $attribute=>$value) {
			$this->data['attributes'][] = $attribute;
		}
	}

}

?>